﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using StoragePeriod.Data;
using StoragePeriod.Common;
using StoragePeriod.Web.UserControls;
using StoragePeriod.Model.RawDict;
using StoragePeriod.BLL.RawDict;
using System.Data;
using StoragePeriod.Web.NopiExcel;
using System.Data.SqlClient;
using System.Configuration;
using StoragePeriod.DBUtility;

namespace StoragePeriod.Web.Nutritionknowledge
{
    public partial class NutrientsStandard : SecurityPage
    {
        T_RawMaterial tRawMaterial = new T_RawMaterial();//原料操作
        T_NutrientComposition tNutrientComposition = new T_NutrientComposition();   //元素含量操作
        T_RawMaterials tRawMaterialType=new T_RawMaterials();//原料大类 操作
        T_RawMaterialsInfo tRawMaterialTypeInfo=new T_RawMaterialsInfo();//原料细类 操作

        public override string PrivCode()
        {
            return "967c9b3589119cc2";
        }

        protected void Page_Load(object sender, EventArgs e)
        {
            LeftTree.SelectedChanging += new MaterialTree.TreeEventDelegate(LeftTree_SelectedChanging);
            LeftLable.Text = "营养素查询";
            if (IsPostBack) return;
        }

        protected void LeftTree_SelectedChanging(Dictionary<string, string> dic)
        {
            if (dic.Count > 0)
            {
                int[] List = new int[dic.ToList().Count()];
                int i = 0;
                dic.ToList().ForEach(p =>
                {
                    RawInfo s = new RawInfo();
                    s.RawId = Convert.ToInt32(p.Key);
                    List[i] = s.RawId;
                    i++;
                });
                List<RawInfo> RawList = SetDataValue(List);
                this.Rep_Rawinfo.DataSource = RawList;
                this.Rep_Rawinfo.DataBind();
            }
        }

        public List<RawInfo> SetDataValue(int[] List)
        {
            int[] RawIdList = List; //获取选中的所有原料
            List<RawInfo> RawInfoList = new List<RawInfo>();

            //遍历所有原料ID
            foreach (int RawId in RawIdList)
            {
                E_NutrientComposition eNutrientComposition = new E_NutrientComposition();
                eNutrientComposition.RawID = RawId;
                List<E_RawElementInfo> RawElementList = tNutrientComposition.GetRawElementList(eNutrientComposition); //获取原料对应元素集合

                //定义原料详细实体
                RawInfo info = new RawInfo();
                info.RawId = RawId;
                if (RawElementList != null)
                {
                    //通过反射进行赋值
                    foreach (E_RawElementInfo item in RawElementList)
                    {
                        typeof(RawInfo).GetProperty(item.Elements).SetValue(info, item.Content, null);
                    }
                }
                E_RawMaterial eRawMaterial = tRawMaterial.GetModel(RawId);
                if (eRawMaterial != null)
                {
                    info.RawName = eRawMaterial.RAWName;
                }
                RawInfoList.Add(info);
            }
            return RawInfoList;

        }

        protected void Btn_Search_Click(object sender, EventArgs e)
        {
            Dictionary<string, string> dic = LeftTree.GetCheckedNodes();
            if (dic.Count > 0)
            {
                int[] List = new int[dic.ToList().Count()];
                int i = 0;
                dic.ToList().ForEach(p =>
                {
                    RawInfo s = new RawInfo();
                    s.RawId = Convert.ToInt32(p.Key);
                    List[i] = s.RawId;
                    i++;
                });
                List<RawInfo> RawInfoList = SetDataValue(List);
                this.Rep_Rawinfo.DataSource = RawInfoList;
                this.Rep_Rawinfo.DataBind();
            }
        }

        /// <summary>
        /// 获取初始化原料详细表
        /// </summary>
        /// <returns></returns>
        public DataTable GetRawInfoDt()
        {
            DataTable dt = new DataTable();
            dt.Columns.Add("原料名称");
            dt.Columns.Add("能量（参考）");
            dt.Columns.Add("蛋白质（参考）");
            dt.Columns.Add("脂肪（参考）");
            dt.Columns.Add("碳水化合物（参考）");
            dt.Columns.Add("VC（参考）");
            dt.Columns.Add("还原糖（参考）");
            dt.Columns.Add("总维A（参考）");
            dt.Columns.Add("硫胺素（参考）");
            dt.Columns.Add("核黄素（参考）");
            dt.Columns.Add("总维E（参考）");
            dt.Columns.Add("钾（参考）");
            dt.Columns.Add("钙（参考）");
            dt.Columns.Add("镁（参考）");
            dt.Columns.Add("铁（参考）");
            dt.Columns.Add("锌（参考）");
            dt.Columns.Add("铜（参考）");
            dt.Columns.Add("氨基酸（参考）");
            dt.Columns.Add("膳食纤维（参考）");
            return dt;
        }

        protected void Btn_Export_Click(object sender, EventArgs e)
        {
            Dictionary<string, string> dic = LeftTree.GetCheckedNodes();
            if (dic.Count > 0)
            {
                int[] List = new int[dic.ToList().Count()];
                int i = 0;
                dic.ToList().ForEach(p =>
                {
                    RawInfo s = new RawInfo();
                    s.RawId = Convert.ToInt32(p.Key);
                    List[i] = s.RawId;
                    i++;
                });
                List<RawInfo> RawInfoList = SetDataValue(List);
                DataTable RawInfoDt = this.GetRawInfoDt();

                foreach (RawInfo item in RawInfoList)
                {
                    DataRow row = RawInfoDt.NewRow();
                    row["原料名称"] = item.RawName;
                    row["能量（参考）"] = item.能量;
                    row["蛋白质（参考）"] = item.蛋白质;
                    row["脂肪（参考）"] = item.脂肪;
                    row["碳水化合物（参考）"] = item.碳水化合物;
                    row["VC（参考）"] = item.维生素C;
                    row["还原糖（参考）"] = "";
                    row["总维A（参考）"] = item.维生素A;
                    row["硫胺素（参考）"] = "";
                    row["核黄素（参考）"] = "";
                    row["总维E（参考）"] = item.维生素E;
                    row["钾（参考）"] = item.钾;
                    row["钙（参考）"] = item.钙;
                    row["镁（参考）"] = item.镁;
                    row["铁（参考）"] = item.铁;
                    row["锌（参考）"] = item.锌;
                    row["铜（参考）"] = item.铜;
                    row["氨基酸（参考）"] = item.氨基酸;
                    row["膳食纤维（参考）"] = item.膳食纤维;
                    RawInfoDt.Rows.Add(row);
                }
                ExcelRender.RenderToExcel(RawInfoDt, HttpContext.Current, Guid.NewGuid().ToString() + ".xls");
            }
        }

        //同步原料数据
        protected void Btn_SynRaw_Click(object sender, EventArgs e)
        {
            this.Btn_SynRaw.Enabled = false;
            //获取原料数据
            SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["CMS_CateringConnectionString"].ToString());
            conn.Open();
            SqlDataAdapter sda = new SqlDataAdapter("select * from RawMaterial", conn);
            DataSet ds = new DataSet();
            sda.Fill(ds);
            List<E_RawMaterial> RawList = new ModelHandler<E_RawMaterial>().FillModel(ds.Tables[0]);

            for (int i = 0; i < RawList.Count; i++)
            {
                bool IsAddElement = false; //判断是否需要添加对应的元素详细
                E_RawMaterial md = RawList[i];
                E_RawMaterial eRawMaterial = tRawMaterial.GetModel(md.id);
                if (eRawMaterial == null) //若不存在则添加
                {
                    tRawMaterial.Add(md);
                    //添加元素含量详细
                    SqlDataAdapter sdaElements = new SqlDataAdapter("select * from NutrientComposition where RawID=" + md.id, conn);
                    DataSet dsElement = new DataSet();
                    sdaElements.Fill(dsElement);
                    List<E_NutrientComposition> ElementList = new ModelHandler<E_NutrientComposition>().FillModel(dsElement.Tables[0]);
                    foreach (E_NutrientComposition item in ElementList)
                    {
                        tNutrientComposition.Add(item);
                        IsAddElement = true;
                    }
                }
                else
                {
                    if (eRawMaterial.IsEdit != 1)//判断是否有做过本地修改
                    {
                        md.PeriodTypeID = eRawMaterial.PeriodTypeID;
                        md.PeriodTypeStorageID = eRawMaterial.PeriodTypeStorageID;
                        md.PeriodTypeKnowledgeID = eRawMaterial.PeriodTypeKnowledgeID;
                        md.PeriodTypeStorKnowledgeID = eRawMaterial.PeriodTypeStorKnowledgeID;
                        tRawMaterial.Update(md); //修改本地原料

                        E_NutrientComposition eNutrientComposition = new E_NutrientComposition();
                        eNutrientComposition.RawID = md.id;
                        tNutrientComposition.RemoveByRawID(eNutrientComposition); //删除库中的元素信息
                        IsAddElement = true;
                    }
                }

                if (IsAddElement)
                {
                    //添加元素含量详细
                    SqlDataAdapter sdaElements = new SqlDataAdapter("select * from NutrientComposition where RawID=" + md.id, conn);
                    DataSet dsElement = new DataSet();
                    sdaElements.Fill(dsElement);
                    List<E_NutrientComposition> ElementList = new ModelHandler<E_NutrientComposition>().FillModel(dsElement.Tables[0]);
                    foreach (E_NutrientComposition item in ElementList)
                    {
                        tNutrientComposition.Add(item);
                    }
                }
            }

            //同步原料大类
            SqlDataAdapter sdaType = new SqlDataAdapter("select * from RawMaterials", conn);
            DataSet dsType = new DataSet();
            sdaType.Fill(dsType);
            List<E_RawMaterials> RawType = new ModelHandler<E_RawMaterials>().FillModel(dsType.Tables[0]);
            foreach (E_RawMaterials item in RawType)
            {
                E_RawMaterials eRawMaterial = tRawMaterialType.GetModel(item.id);
                if (eRawMaterial == null) //若不存在则添加
                {
                    tRawMaterialType.Add(item);
                }
                else
                {
                    tRawMaterialType.Update(item);
                }
            }

            //同步原料细类
            SqlDataAdapter sdaTypeInfo = new SqlDataAdapter("select * from RawMaterialsInfo", conn);
            DataSet dsTypeInfo = new DataSet();
            sdaTypeInfo.Fill(dsTypeInfo);
            List<E_RawMaterialsInfo> RawTypeInfo = new ModelHandler<E_RawMaterialsInfo>().FillModel(dsTypeInfo.Tables[0]);
            foreach (E_RawMaterialsInfo item in RawTypeInfo)
            {
                E_RawMaterialsInfo eRawMaterial = tRawMaterialTypeInfo.GetModel(item.id);
                if (eRawMaterial == null) //若不存在则添加
                {
                    tRawMaterialTypeInfo.Add(item);
                }
                else
                {
                    tRawMaterialTypeInfo.Update(item);
                }
            }

            conn.Close();
            this.Btn_SynRaw.Enabled = true;
            ClientScript.RegisterStartupScript(this.GetType(), "alert", "<script>alert('同步完成！');</script>");
        }
    }
}